<template>
    <view class="lease-order-lists">
        <!-- Tabs -->
        <view class="tabs-container">
            <u-tabs 
              :list="tabs" 
              :is-scroll="false" 
              :current="tabCurrent" 
              font-size="28"
              active-color="#333333"
              bar-width="80"
              :bar-style="{'background-color': '#24A3FF'}"
              @change="changeTab" 
            />
        </view>
        
        <!-- List Content -->
        <view class="main">
            <block v-for="(item, index) in lists" :key="item.id">
                <view class="order-item">
                    <view class="order-header">
                        <view>{{ item.create_time }}</view>
                        <view :style="{color: orderStatusMap[item.order_status].color}">
							{{ orderStatusMap[item.order_status].name }}
						</view>
                    </view>
                    
                    <view class="order-content">
                        <block v-for="(subItem, subIndex) in item.lease_order_goods" :key="subItem.id">
                            <lease-order-goods :image="subItem.image" @tap="goOrderDetail(item.id)">
                                <template #name>{{ subItem.goods_name }}</template>
                                <template #specs>
                                    {{ subItem.spec_value }}，
                                    {{ subItem.periods }}{{ getPeriodsUnit(subItem.periods_attribute) }}
                                </template>
                                <template #price>
                                    <price 
                                      :content="oneDayPrice(subItem.periods_attribute, subItem.issue_rent)" 
                                      mainSize="38rpx" 
                                      minorSize="24rpx" 
                                      color="#333333" 
                                      :isPrefix="true" 
                                      :isSuffix="true" 
                                    />
                                    <text>（x{{ subItem.periods }}期）</text>
                                </template>
                            </lease-order-goods>
                        </block>
                        <view class="order-pay">
                            <text class="order-pay-lable">应付款:</text>
                            <price 
                              :content="item.lease_order_goods[0].first_pay_amount" 
                              mainSize="38rpx" 
                              minorSize="24rpx" 
                              color="#333333" 
                              :isPrefix="true" 
                            />
                        </view>
                    </view>
                    
                    <view class="order-footer">
						<block v-for="subIndex in getButtons(item.order_status, item)" :key="subIndex">
							<view class="order-button" 
							  :class="[buttonList[subIndex]['class']]" 
							  @tap="onOrderButton(buttonList[subIndex].key, item)"
							>
								{{ buttonList[subIndex].name }}
							</view>
						</block>
					</view>
                </view>
            </block>
        </view>
        
        <!-- Footer -->
        <view>
            <loading-footer :status="status" />
        </view>
		
		<!-- Widget -->
		<view>
			<!-- 取消订单 -->
			<u-modal v-model="showCloseOrderModal" 
			  content="取消订单" 
			  :show-cancel-button="true" 
			  @confirm="handleOrderClose" 
			/>
			
			<!-- 删除订单 -->
			<u-modal v-model="showDelOrderModal" 
			  content="删除订单" 
			  :show-cancel-button="true" 
			  @confirm="handleOrderDel" 
			/>
			
			<!-- 确认收货 -->
			<u-modal v-model="showConfirmOrderModal"
			  content="确认收货" 
			  :show-cancel-button="true" 
			  @confirm="handleOrderConfirm" 
			/>
			
			<!-- 续租 -->
			<u-popup v-model="showReletOrderPopup" mode="center" border-radius="20">
				<view class="relet">
					<view class="relet-title">续租</view>
					<view class="relet-content">
						<view class="relet-label">请选择租期</view>
						<view class="relet-list">
							<block v-for="item in reletList" :key="item.periods_id">
								<view class="relet-item" 
								  :class="{'relet-item--active': relet == item.periods_id}"
								  @tap="relet = item.periods_id"
								>
									{{ item.name }}
								</view>
							</block>
						</view>
					</view> 
					<view class="relet-widget">
						<view class="relet-cancel" @tap="showReletOrderPopup = false">取消</view>
						<view class="relet-confirm" @tap="handleRelet">确认</view>
					</view>
				</view>
			</u-popup>
			
			<!-- 还机 -->
			<u-popup v-model="showReturnOrderPopup" mode="center" border-radius="20">
				<view class="return">
					<view class="return-title">温馨提示</view>
					<view class="return-content">您当前租期未到期，提前还机需支付相应的违约金，是否确认还机？</view> 
					<view class="return-widget">
						<view class="return-cancel" @tap="showReturnOrderPopup = false">取消</view>
						<view class="return-confirm" @tap="goReturnOrder">确认</view>
					</view>
				</view>
			</u-popup>
		</view>
    </view>
</template>


<script>
    import { 
		getLeaseOrderList,		// 订单列表
		leaseOrderCancel,		// 取消订单
		leaseOrderDel,			// 删除订单
		leaseOrderConfirm,		// 确认收货
		leaseOrderRelet,		// 续租
		leaseReturnCheck,		// 还机验证
	} from '@/api/lease.js';
	import { prepay } from '@/api/app';
	import { wxpay } from '@/utils/pay'
    import { loadingType } from '@/utils/type';
    import { loadingFun } from "@/utils/tools";
    
    export default {
        data() {
            return {
				showDelOrderModal: false,		// 删除订单Modal
				showCloseOrderModal: false,		// 取消订单Modal
				showConfirmOrderModal: false,	// 确认收货Modal
				showReletOrderPopup: false,		// 续租 Popup
				showReturnOrderPopup: false, 	// 还机 Popup
				reletList: [],					// 续租期 数据列表
				relet: '',						// 选择的租期
				currentActiveID: '',			// 当前选中的订单ID
                // Tabs列表
                tabs: [{
                    key: 'all',
                	name: '全部'
                }, {
                    key: 'pay',
                	name: '待付款'
                }, {
                    key: 'delivery',
                	name: '待收货'
                },{
                    key: 'renting',
                	name: '租用中'
                },{
                    key: 'finish',
                	name: '已完成'
                }],
                tabCurrent: 0,                  // 当前Tab索引  [0-全部; 1-待付款; 2-待收货; 3-租用中; 4-已完成;]
                lists: [],                      // 当前订单数据列表 
                page: 1,                        // 当前页数状态
                status: loadingType.LOADING,    // 当前加载状态
				// 订单状态映射表
				orderStatusMap: [
					{
						name: '待付款',
						color: '#24A3FF'
					},
					{
						name: '待发货',
						color: '#24A3FF'
					},
					{
						name: '待收货',
						color: '#24A3FF'
					},
					{
						name: '租用中',
						color: '#24A3FF'
					},
					{
						name: '已完成',
						color: '#999999'
					},
					{
						name: '已关闭',
						color: '#999999'
					}
				],
				// 按钮列表
				buttonList: {
					0: {
						key: 'pay',
						name: '立即付款',
						class: 'order-button--active'
					},
					1: {
						key: 'repayment',
						name: '去还款',
						class: 'order-button--active'
					},
					2: {
						key: 'receive',
						name: '确认收货',
						class: 'order-button--normal'						
					},
					3: {
						key: 'evaluate',
						name: '去评价',
						class: 'order-button--normal'
					},
					4: {
						key: 'return',
						name: '还机',
						class: 'order-button--normal'
					},
					5: {
						key: 'buy',
						name: '买断',
						class: 'order-button--normal'
					},
					6: {
						key: 'buy_detail',
						name: '买断详情',
						class: 'order-button--normal'
					},
					7: {
						key: 'return_detail',
						name: '还机详情',
						class: 'order-button--normal'
					},
					8: {
						key: 'relet',
						name: '续租',
						class: 'order-button--normal'
					},
					9: {
						key: 'close',
						name: '取消订单',
						class: 'order-button--inactive'
					},
					10: {
						key: 'express',
						name: '查看物流',
						class: 'order-button--inactive'
					},
					11: {
						key: 'del',
						name: '删除订单',
						class: 'order-button--inactive'
					}
				}
            }
        },
        
        methods: {
            // 切换Tabs
            changeTab(index) {
                this.tabCurrent = index;
            },
			
			// 输出分期单位
			getPeriodsUnit(value) {
			    switch(value) {
			        case 'is_week': return '周';
			        case 'is_month': return '个月';
			    }
			},
			
			// 每天多少钱
			oneDayPrice(unit, issueRent) {
				switch(unit) {
					case 'is_week':
						return Number((issueRent / 7).toString().match(/^\d+(?:\.\d{0,2})?/));
					case 'is_month': 
						return Number((issueRent / 30).toString().match(/^\d+(?:\.\d{0,2})?/));
				}
			},	
			
			// 获取该订单应有的按钮
			getButtons(status, order) {
				switch(status) {
					// 待付款
					case 0: return [0, 9];
					// 待发货
					case 1: return [9];
					// 待收货
					case 2: return [2, 10];
					// 租用中
					case 3: 
						const btns = [5, 8];
						// if (order.is_repayment * 1) btns.push(1);
						// if (order.is_return_show * 1) btns.unshift(4);
						// if (order.is_return_details_show * 1) btns.unshift(7);
						// if (order.is_buyout_details_show * 1) btns.unshift(6);
												if (order.is_repayment * 1) btns.splice(btns.length, 1, 1);
												if (order.is_return_show * 1) btns.splice(0, 0, 4);

						return btns;
					// 已完成
					case 4: return [9];
					// 已关闭
					case 5: return [11];
				}
			},
			
			// 订单按钮
			onOrderButton(event, order) {
				console.log(order);
				this.currentActiveID = order.id;
				switch(event) {
					// 立即付款
					case 'pay': 
						return this.onOrderPay(order);
					// 去还款
					case 'repayment': 
						return this.onOrderRepayment();
					// 确认收货
					case 'receive': 
						return this.onOrderReceive();
					// 去评价
					case 'evaluate': 
						return this.onOrderEvaluate();
					// 还机
					case 'return': 
						return this.onOrderReturn();
					// 买断
					case 'buy': 
						return this.onOrderBuy();
					// 买断详情
					case 'buy_detail': 
						return this.onOrderBuyDetail();
					// 还机详情
					case 'return_detail': 
						return this.onOrderReturnDetail();
					// 续租
					case 'relet': 
						return this.onOrderRelet();
					// 取消订单
					case 'close': 
						return this.onOrderClose();
					// 查看物流
					case 'express': 
						return this.onOrderExpress();
					// 删除订单
					case 'del': 
						return this.onOrderDel();
				}
			},
			
			// 按下立即付款按钮
			onOrderPay(order) {
				const payWay = order.pay_way;
				const id = this.currentActiveID;
				
				switch(payWay) {
					// 微信支付
					case 1: return this.handlePayWeChat(id);
					// 支付宝支付
					case 2: return;
					// 余额支付
					case 3: return;
				}
			},
			
			// 按下去还款按钮
			onOrderRepayment() {
				const id = this.currentActiveID;
				uni.navigateTo({
					url: `/bundle/pages/lease_bill/lease_bill?id=${id}`
				})
			},
			
			// 按下确认收货按钮
			onOrderReceive() {
				this.showConfirmOrderModal = true;
			},
			
			// 按下去评价按钮
			onOrderEvaluate() {
				
			},
			
			// 按下还机按钮
			onOrderReturn() {
				const id = this.currentActiveID;
				leaseReturnCheck({
					id,
					action: 'check'
				}).then(res => {
					const code = res.code;
					console.log(res);
					if (code == 1) {
						uni.redirectTo({
							url: `/bundle/pages/lease_return_detail/lease_return_detail?id=${id}`
						})
					} else {
						this.showReturnOrderPopup = true;
					}
				})
			},
			
			// 按下买断按钮
			onOrderBuy() {
				
			},
			
			// 按下买断详情按钮
			onOrderBuyDetail() {
				
			},
			
			// 按下还机详情按钮
			onOrderReturnDetail() {
				const id = this.currentActiveID;
				uni.redirectTo({
					url: `/bundle/pages/lease_return_detail/lease_return_detail?id=${id}`
				})
			},
			
			// 按下续租按钮
			onOrderRelet() {
				uni.showLoading({ title: '加载中' });
				const id = this.currentActiveID;
				leaseOrderRelet({
					id,
					action: 'info'
				}).then(res => {
					uni.hideLoading();
					if (res.code != 1) return;
					this.showReletOrderPopup = true;
					const data = res.data;
					this.reletList = data;
					this.relet = data[0].periods_id;
				});
			},
			
			// 按下取消订单按钮
			onOrderClose(id) {
				this.showCloseOrderModal = true;
			},
			
			// 按下查看物流按钮
			onOrderExpress() {
				const id = this.currentActiveID;
				uni.navigateTo({
					url: `/bundle/pages/goods_logistics/goods_logistics?id=${id}`
				})
			},
			
			// 按下删除订单按钮
			onOrderDel() {
				this.showDelOrderModal = true;
			},
			
			
			// 取消订单处理
			handleOrderClose() {
				const id = this.currentActiveID;
				leaseOrderCancel({ id }).then(res => this.handleRefresh());
			},
			
			// 删除订单处理
			handleOrderDel() {
				const id = this.currentActiveID;
				leaseOrderDel({ id }).then(res => this.handleRefresh());
			},
			
			// 确认收货处理
			handleOrderConfirm() {
				const id = this.currentActiveID;
				leaseOrderConfirm({ id }).then(res => this.handleRefresh());
			},
			
			// 续租处理
			handleRelet() {
				const id = this.currentActiveID;
				
				leaseOrderRelet({
					id,
					periods_id: this.relet,
					action: 'submit',
				}).then(res => {
					this.showReletOrderPopup = false;
					if (res.code != 1) return;
					uni.showToast({ title: '续租成功', icon: 'success' });
				});
			},
			
			// 微信支付
			handlePayWeChat(id) {
				prepay({
					from: 'lease_order',
					order_id: id
				}).then(res => {
					const code = res.code;
					const data = res.data;
					
					wxpay(data).then(res => {
						if(res == 'success') {
							this.handleRefresh();
							uni.navigateTo({
								url: '/bundle/pages/lease_pay_result/lease_pay_result'
								  + '?id=' + id 
							});
						}
					})
				});
			},
			
			
			// 查看订单详情
			goOrderDetail(id) {
				uni.navigateTo({
					url: '/bundle/pages/lease_order_detail/lease_order_detail'
					  + '?id=' + id
				})
			},
			
			// 前往还机
			goReturnOrder() {
				const id = this.currentActiveID;
				this.showReturnOrderPopup = false;
				uni.navigateTo({
					url: '/bundle/pages/lease_goods_return/lease_goods_return'
					  + '?id=' + id
				})
			},
            
            // 列表数据请求
            reqLeaseOrderLists(type) {
                loadingFun(
                    getLeaseOrderList,
                    this.page,
                    this.lists,
                    this.status,
                    { type }
                ).then(res => {
                    if (!res) return;
                    this.page = res.page
                    this.lists = res.dataList
                    this.status = res.status
                });
            },
            
            // 重置请求状态
            reset() {
                this.lists = [];
                this.page = 1;
                this.status = loadingType.LOADING;
            },
			
			// 刷新数据
			handleRefresh() {
				// 重置状态
				this.reset();
				// 请求对应tab的列表数据
				const type = this.tabs[this.tabCurrent].key;
				this.reqLeaseOrderLists(type);
			}
        },
        
        watch: {
            tabCurrent(value) {
				this.handleRefresh();
            }
        },
        
        onLoad(options) {
            // type: all-全部；pay-待付款；delivery-待收货；renting-租用中；finish-已完成；close-已关闭
            // const type = options.type || 'all';
            // this.reqLeaseOrderLists(type);
        },
		
		onShow() {
			this.handleRefresh();
		},
        
        // 上拉加载更多
        onReachBottom() {
            const type = this.tabs[this.tabCurrent].key;
            this.reqLeaseOrderLists(type);
        },
    }
</script>


<style scoped>
    .lease-order-lists {
        padding-top: 88rpx;
    }
    
    .tabs-container {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 999;
    }
    
    .main {
        padding: 20rpx;
    }
    
    .order-item {
        padding: 0 20rpx;
        border-radius: 10px;
        background-color: #FFFFFF;
    }
    
    .order-item:nth-child(n+2) {
        margin-top: 20rpx;
    }
    
    .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 80rpx;
        border-bottom: 1px solid #E5E5E5;
        font-size: 28rpx;
    }
    
    .order-content {
        padding: 20rpx 0;
    }
    
    .order-pay {
        padding-top: 20rpx;
        text-align: right;
    }
	
	.order-pay-lable {
		margin-right: 10rpx;
		font-size: 24rpx;
		color: #999999;
	}
    
    .order-footer {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        height: 100rpx;
        border-top: 1px solid #E5E5E5;
    }
	
	.order-button {
		box-sizing: border-box;
		padding: 10rpx 40rpx;
		border-radius: 100px;
		font-size: 26rpx;
	}
	
	.order-button:nth-child(n+2) {
		margin-left: 20rpx;
	}
	
	.order-button--active {
		background-color: #24A3FF;
		color: #FFFFFF;
	}
	
	.order-button--inactive {
		border: 1px solid #D7D7D7;
		background-color: #FFFFFF;
		color: #666666;
	}
	
	.order-button--normal {
		background-color: #FFFFFF;
		border: 1px solid #24A3FF;
		color: #24A3FF;
	}
	
	.relet,
	.return {
		width: 640rpx;
		padding: 30rpx 40rpx;
		background-color: #FFFFFF;
	}
	
	.relet-title,
	.return-title {
		padding-bottom: 30rpx;
		text-align: center;
		font-weight: 500;
		font-size: 34rpx;
		color: #333333;
	}
	
	.return-content {
		text-align: center;
		font-size: 32rpx;
		color: #333333;
	}
	
	.relet-label {
		font-size: 28rpx;
		color: #333333;
	}
	
	.relet-list {
		display: flex;
		flex-wrap: wrap;
	}
	
	.relet-item {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 152rpx;
		height: 58rpx;
		margin: 20rpx 20rpx 0 0;
		border-radius: 50px;
		font-size: 26rpx;
		color: #333333;
		background-color: #F4F4F4;
	}
	
	.relet-item--active {
		background-color: #E8F6FF;
		box-shadow: 0 0 0 1px #24A3FF;
		color: #24A3FF;
	}
	
	.relet-widget,
	.return-widget {
		display: flex;
		justify-content: space-between;
		margin-top: 84rpx;
	}
	
	.relet-cancel,
	.relet-confirm,
	.return-cancel,
	.return-confirm {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 268rpx;
		height: 74rpx;
		font-size: 32rpx;
		border-radius: 50px;
	}
	
	.relet-cancel,
	.return-cancel {
		background-color: #F6F6F6;
		color: #666666;
	}
	
	.relet-confirm,
	.return-confirm {
		background-color: #24A3FF;
		color: #FFFFFF;
	}
</style>
